package tech.wetech.admin3.sys.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tech.wetech.admin3.sys.model.Message;
import tech.wetech.admin3.sys.repository.MsgCenterRepository;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class MsgCenterService {
  @Autowired
  private MsgCenterRepository msgCenterRepository;

  public Message createMessage(String title, String content, String email) {
    Message message = new Message();
    message.setTitle(title);
    message.setContent(content);
    message.setEmail(email);
    message.setSender("系统");
    message.setRead(false);
    message.setCreateDate(LocalDateTime.now());
    return msgCenterRepository.save(message);
  }


  public List<Message> getMessagesForUser(String email) {
    return msgCenterRepository.findByEmail(email);
  }

  public List<Message> getUnreadMessagesForUser(String email) {
    return msgCenterRepository.findByEmailAndIsRead(email, false);
  }

  public Message markMessageAsRead(Integer id) {
    Message message = msgCenterRepository.findById(id).orElse(null);
    if (message != null) {
      message.setRead(true);
      return msgCenterRepository.save(message);
    }
    return null;
  }

  public void deleteReadMessages(String email) {
    List<Message> messages = msgCenterRepository.findByEmailAndIsRead(email, true);
    msgCenterRepository.deleteAll(messages);
  }

  public void deleteSpecificMessages(List<Integer> ids) {
    List<Message> messages = msgCenterRepository.findAllById(ids);
    msgCenterRepository.deleteAll(messages);
  }

  public List<Message> searchMessages(String email, String digitalName) {
    return msgCenterRepository.findByEmailAndContentContainingIgnoreCase(email, digitalName);
  }

}
